package cn.goktech.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;

import cn.goktech.entity.Type;
import cn.goktech.service.ITypeService;
import cn.goktech.service.impl.TypeServiceImpl;

@WebServlet("/TypeServlet")
public class TypeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		String task = request.getParameter("task");

		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		
		ITypeService typeService = new TypeServiceImpl();
		
		if("queryTypeList".equals(task)){
			String username = (String)session.getAttribute("username");
			List<Type> typeList = typeService.typeList(username);
			String jsonString = JSON.toJSONString(typeList);
			out.print(jsonString);
		}else if("addType".equals(task)){
			String username = (String)session.getAttribute("username");
			String type = request.getParameter("type");
			Type type2 = new Type();
			type2.setUsername(username);
			type2.setType(type);
			int add = typeService.add(type2);
			if(add>0){
				List<Type> typeList = typeService.typeList(username);
				String jsonString = JSON.toJSONString(typeList);
				out.print(jsonString);
			}
		}else if("updateType".equals(task)){
			String username = (String)session.getAttribute("username");
			int id=Integer.parseInt(request.getParameter("id"));
			String type = request.getParameter("type");
			Type type2 = new Type();
			type2.setId(id);
			type2.setType(type);
			int update = typeService.update(type2);
			if(update>0){
				List<Type> typeList = typeService.typeList(username);
				String jsonString = JSON.toJSONString(typeList);
				out.print(jsonString);
			}
		}else if("delType".equals(task)){
			String username = (String)session.getAttribute("username");
			int id=Integer.parseInt(request.getParameter("id"));
			int del = typeService.delete(id);
			if(del>0){
				List<Type> typeList = typeService.typeList(username);
				String jsonString = JSON.toJSONString(typeList);
				out.print(jsonString);
			}
		}
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
